import axios from 'axios'

import { getLocalStorage } from '../utils/utils'
import { ServerURL } from '../utils/config'

const instance = axios.create({
    baseURL: ServerURL,
    timeout: 100000
})

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    config.headers['authorization'] = getLocalStorage('token')
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

export function PostApi(url, user) {
    return new Promise((resolve, reject) => {
        instance.post(url, user)
            .then(res => {
                return resolve(res)
            })
            .catch(err => {
                return reject(`${url}` + err)
            })
    })
}
export function GetApi(url, params = {}) {
    return new Promise((resolve, reject) => {
        instance.get(url, { params })
            .then(res => {
                return resolve(res)
            })
            .catch(err => {
                return reject(`${url}` + err)
            })
    })
}

export function Put(url, data) {
    return instance.put(url, data)
}

export function Del(url) {
    return instance.delete(url)
}